package vip.zhenzicheng.test.juc.lock.util;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhenzicheng
 * @date 2023-02-07 15:19
 */
public class ExchangerCase {
  private static final Exchanger<String> exchanger = new Exchanger<>();
  private static final ExecutorService threadPool = Executors.newFixedThreadPool(2);

  public static void main(String[] args) {

    threadPool.execute(() -> {
      try {
        String A = "12379871924sfkhfksdhfks";
        // 将 A 字符串给交换器并等待交换器返回其它线程交换的数据，阻塞
        String exchange = exchanger.exchange(A);
        System.out.println("交换后：" + exchange);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    });

    threadPool.execute(() -> {
      try {
        String B = "32423423jknjkfsbfj";
        // 将"exchange data"字符串给交换器并获取上一次的交换结果，也即 A 的字符串
        String A = exchanger.exchange("exchange data");
        System.out.println("A和B数据是否一致：" + A.equals(B));
        System.out.println("A= " + A);
        System.out.println("B= " + B);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    });
    threadPool.shutdown();
  }
}
